package message.broken;

import org.hibernate.cfg.Configuration;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.SessionFactory;
import org.hibernate.Session;
import org.hibernate.Transaction;

import org.testng.annotations.Test;
import org.testng.annotations.BeforeClass;

public class BrokenMessageTest {
	SessionFactory sessionFactory = null;
	public BrokenMessageTest() {
	}
	@BeforeClass
	public void setup(){
		Configuration config = new Configuration();
		config.configure();
		StandardServiceRegistryBuilder serviceRegisteryBuilder = new StandardServiceRegistryBuilder();
		serviceRegisteryBuilder.applySettings(config.getProperties());
		sessionFactory = config.buildSessionFactory(serviceRegisteryBuilder.build());
	}
//	@Test
	public void testMessage(){
		
		Long emailId;
		Long messageId;
		
		EMail email = new EMail();
		email.setSubject("Hi");
		
		Message message = new Message();
		message.setContent("This is broken message");
		email.setMessage(message);
		message.setEmail(email);//
		
		Session session = sessionFactory.openSession();
		Transaction txn = session.beginTransaction();
		session.save(email);
		//session.save(message);
		txn.commit();
		session.close();
		
		emailId = email.getId();
		messageId = email.getId();
		
		session = sessionFactory.openSession();
		txn = session.beginTransaction();
		email = (EMail)session.get(EMail.class, emailId);
		message =(Message)session.get(Message.class, messageId);
		System.out.println();
		System.out.println();
		System.out.println("E mail "  +email);
		System.out.println("Message " +message);
		System.out.println("EMail --> Message = " + email.getMessage());
		System.out.println("Message --> EMail = " + message.getEmail());
		
		txn.commit();
		session.close();
		
	}
	
	@Test
	public void testMessage2(){
		
		Long emailId;
		Long messageId;
		
		EMail2 email = new EMail2();
		email.setSubject("Hi");
		
		Message2 message = new Message2();
		message.setContent("This is broken message");
		email.setMessage(message);
		message.setEmail(email);
		
		Session session = sessionFactory.openSession();
		Transaction txn = session.beginTransaction();
		session.save(email);
//		session.save(message);
		txn.commit();
		session.close();
		
		emailId = email.getId();
		messageId = email.getId();
		
		session = sessionFactory.openSession();
		txn = session.beginTransaction();
		email = (EMail2)session.get(EMail2.class, emailId);
		message =(Message2)session.get(Message2.class, messageId);
		System.out.println();
		System.out.println();
		System.out.println("E mail "  +email);
		System.out.println("Message " +message);
		System.out.println("EMail --> Message = " + email.getMessage());
		System.out.println("Message --> EMail = " + message.getEmail());
		
		txn.commit();
		session.close();
		
		session = sessionFactory.openSession();
		txn = session.beginTransaction();
		session.delete(email);
		txn.commit();
		session.close();
	}

}
